//
//  ViewController.m
//  Kiosk
//
//  Created by Raffael Reichelt on 17.12.12.
//  Copyright (c) 2012 Raffael Reichelt. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize toolbar =_toolbar;
@synthesize webView = _webView;
@synthesize StartingPage , PortalMode, LearningMode, showAlerts;
@synthesize managedObjectContext = _managedObjectContext;

@synthesize soundFileURLRef;
@synthesize soundFileObject;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    NSURL *tapSound   = [[NSBundle mainBundle] URLForResource: @"oh"
                                                withExtension: @"wav"];
    
    // Store the URL as a CFURLRef instance
    self.soundFileURLRef = (__bridge CFURLRef) tapSound;
    
    // Create a system sound object representing the sound file.
    AudioServicesCreateSystemSoundID (
                                      
                                      soundFileURLRef,
                                      &soundFileObject
                                      );
    UIApplication *myApp = [UIApplication sharedApplication];

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self
               selector:@selector(defaultsChanged:)
                   name:NSUserDefaultsDidChangeNotification
                 object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:myApp];
    [self readPreferences];
    if (Journal == nil) {
        Journal = [self getJournal];
    }

    [self loadHome:self];
}
- (void)defaultsChanged:(NSNotification *)notification {
    // Get the user defaults
    NSUserDefaults *defaults = (NSUserDefaults *)[notification object];
    if (defaults != nil){
        [self readPreferences];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    [self writeJournal:Journal];
    
}

// Soll der aktuelle Request geladen werden?
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    

    NSString *myCurrentRequest = request.URL.host;

    NSURL* start = [[NSURL alloc]initWithString:StartingPage];

    // Die Hilfe wird immer angezeigt
    if (myCurrentRequest == Nil) return YES;
    
    // Wenn wir im Learning mode sind unbedingt
    if (LearningMode) {
        return YES;
    }
    
    // Wenn wir im Portalmode sind nur, wenn die aufrufende Seite der eingestellten Startseite entspricht.
    else if (PortalMode) {
        if (([self.webView.request.URL.host caseInsensitiveCompare:start.host] == NSOrderedSame)) return YES;
    }
    
    
    // Zu guter Letzt noch die vorhandenen hosts aus den Favoriten ... aber keinen Schritt weiter
    for (NSInteger i = 0; i < [[Journal objectForKey:@"Journal"]count]; i++) {

        NSURL *tmpURL = [[NSURL alloc]initWithString:[[[Journal objectForKey:@"Journal"]objectAtIndex:i]objectAtIndex:2]];
        
        NSString *tmpURLhost = tmpURL.host;
        
        if ([tmpURLhost isEqualToString:myCurrentRequest]) {
         return YES;   
        }
    }
    
    // Ansonsten leider nicht
    if (showAlerts) {
        AudioServicesPlaySystemSound (soundFileObject);
    }
    return NO;
}


- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
}

- (void) webViewDidFinishLoad:(UIWebView *)webView {
    
    if (LearningMode) {
        NSString *title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        NSString *tmpTitle = [NSString alloc];
        NSString *url = self.webView.request.URL.absoluteString;
        
        UIGraphicsBeginImageContext(CGSizeMake(600,400));
        CGContextRef context = UIGraphicsGetCurrentContext();
        [self.webView.layer renderInContext:context];
        UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        
        NSArray *entry = [NSArray arrayWithObjects:title, thumbnail, url, nil];
        
        if ([Journal objectForKey:@"Journal"] == nil) {
            NSMutableArray *array = [NSMutableArray arrayWithObject:entry];
            [Journal setValue:array forKey:@"Journal"];
        }
        else{
            BOOL test = YES;
            for (NSInteger i = 0; i < [[Journal objectForKey:@"Journal"]count]; i++) {
                tmpTitle = [[[Journal objectForKey:@"Journal"]objectAtIndex:i]objectAtIndex:0];
                if ([tmpTitle isEqual:title]){
                    test = NO;
                    break;
                }
            }
            if (test) {
                NSMutableArray *array = [NSMutableArray arrayWithArray:[Journal objectForKey:@"Journal"]];
                [array addObject:entry];
                [Journal setValue:array forKey:@"Journal"];
            }
            
        }
    }
    [self updateButtons];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
}

- (IBAction)loadHome:(id)sender {

    if ([StartingPage length] > 0){
        NSURL *url = [[NSURL alloc] initWithString:StartingPage];
        [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
   }
    else [self showInfo:self];    
}

- (void) readPreferences {
  
    StartingPage = [[NSUserDefaults standardUserDefaults] stringForKey:@"home_preference"];
    PortalMode = [[NSUserDefaults standardUserDefaults] boolForKey:@"portal_preference"];
    LearningMode = [[NSUserDefaults standardUserDefaults] boolForKey:@"learn_preference"];
    showAlerts = [[NSUserDefaults standardUserDefaults] boolForKey:@"alert_preference"];
}

- (void) updateButtons {
    
    self.back.enabled = self.webView.canGoBack;
    self.forward.enabled = self.webView.canGoForward;
    if ([[Journal objectForKey:@"Journal"] count]>0) self.info.enabled = YES;
    else self.info.enabled = NO;
}

- (IBAction)showInfo:(id)sender {
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"html"]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (IBAction)showFavorites:(id)sender
{
    JournalViewController *controller = [[JournalViewController alloc] initWithNibName:@"JournalViewController" bundle:nil];
    controller.delegate = self;
    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:controller animated:YES];
    
}

- (void)journalViewControllerDidFinish:(JournalViewController *)controller
{
    [self writeJournal:Journal];
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction) loadURL: (NSString *) url {
    
    NSURL *myurl = [[NSURL alloc]initWithString:url];
    NSURLRequest* request = [[NSURLRequest alloc]initWithURL:myurl];
    [self.webView loadRequest:request];
}

- (NSMutableDictionary *) getJournal {
    if (Journal == nil) {
        Journal = [self readJournal];
    }
    return Journal;
}

- (NSMutableDictionary *) readJournal{
    
    // get paths from root direcory
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    // get documents path
    NSString *documentsPath = [paths objectAtIndex:0];
    // get the path to our Data/plist file
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Kiosk.plist"];
    
    // check to see if Data.plist exists in documents
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
    {
        // if not in documents, get property list from main bundle
        plistPath = [[NSBundle mainBundle] pathForResource:@"Kiosk" ofType:@"plist"];
    }
    
    // read property list into memory as an NSData object
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
    NSString *errorDesc = nil;
    NSPropertyListFormat format;
    // convert static property liost into dictionary object
    NSMutableDictionary *dictionary = (NSMutableDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
    if (!dictionary)
    {
        NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
        return nil;
    }
    return dictionary;
}

- (BOOL) writeJournal:(NSMutableDictionary *)dictionary {
    // get paths from root direcory
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    // get documents path
    NSString *documentsPath = [paths objectAtIndex:0];
    // get the path to our Data/plist file
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Kiosk.plist"];
    
    NSString *error = nil;
    // create NSData from dictionary
    NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:Journal format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
    
    // check is plistData exists
    if(plistData)
    {
        // write plistData to our Data.plist file
        [plistData writeToFile:plistPath atomically:YES];
        return  YES;
    }
    else
    {
        NSLog(@"Error in done: %@", error);
        return NO;
    }
}

- (BOOL) setJournal: (NSMutableDictionary *) dictionary {
    
    if ([Journal isEqualToDictionary:dictionary]) {
        Journal = dictionary;
    }
    return YES;
}

@end
